package com.example.taobaounion.view.fragment;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;
import com.example.taobaounion.constant.Constants;
import com.example.taobaounion.manager.PresenterManager;
import com.example.taobaounion.model.domain.Categories;
import com.example.taobaounion.model.domain.HomePagerContent;
import com.example.taobaounion.model.domain.ILinearItemInfo;
import com.example.taobaounion.presenter.impl.CategoryPagerPresenter;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.SizeUtils;
import com.example.taobaounion.utils.TicketUtil;
import com.example.taobaounion.utils.ToastUtils;
import com.example.taobaounion.view.adapter.HomePageContentAdapter;
import com.example.taobaounion.view.adapter.LooperPagerAdapter;
import com.example.taobaounion.view.callback.ICategoryPagerCallback;
import com.example.taobaounion.view_component.AutoLoopViewPager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.custom.TbNestedScrollView;

import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class HomePagerFragment extends BaseFragment {

    // Constant
    private static final String TAG = "HomePagerFragment";

    private CategoryPagerPresenter mCategoryPagerPresenter;
    private ICategoryPagerCallback mICategoryPagerCallback;
    private int mMaterialId;


    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;

    @BindView(R.id.home_pager_title)
    public TextView currentCategoryTitle;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_parent)
    public LinearLayout mHomePagerParent;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout mTwinklingRefreshLayout;

    @BindView(R.id.home_pager_nested_scroller)
    public TbNestedScrollView mTbNestedScrollView;

    @BindView(R.id.home_pager_header_container)
    public LinearLayout mHomeHeaderContainer;

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    // Adapter
    private HomePageContentAdapter mContentAdapter;
    private LooperPagerAdapter mLooperPagerAdapter;

    public static HomePagerFragment newInstance(Categories.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();

        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIALID, category.getId());

        homePagerFragment.setArguments(bundle);

        return homePagerFragment;
    }

    @Override
    protected void initView(View view) {

        // 设置recyclerView 的显示方式
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));


        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = SizeUtils.dip2px(Objects.requireNonNull(getContext()), 1.5f);
                outRect.bottom = SizeUtils.dip2px(Objects.requireNonNull(getContext()), 1.5f);
            }
        });

        // 设置（选择）刷新控件的样式
        mTwinklingRefreshLayout.setEnableRefresh(false);
        mTwinklingRefreshLayout.setEnableLoadmore(true);
    }

    protected void initAdapter() {

        mContentAdapter = new HomePageContentAdapter();
        mContentList.setAdapter(mContentAdapter);

        mLooperPagerAdapter = new LooperPagerAdapter();
        looperPager.setAdapter(mLooperPagerAdapter);
    }

    @Override
    protected void initListener() {

        mHomePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                int headerHeight = mHomeHeaderContainer.getMeasuredHeight();


                mTbNestedScrollView.setHeight(headerHeight);

                int measuredHeight = mHomePagerParent.getMeasuredHeight();

                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();

                layoutParams.height = measuredHeight;

                mContentList.setLayoutParams(layoutParams);

                if (measuredHeight != 0) {
                    mHomePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        mLooperPagerAdapter.setOnLoopPageItemClickListener(dataBean -> {
            LogUtils.d(TAG, "looper... event");
            handleItemClick(dataBean);
        });

        mContentAdapter.setOnListenerItemClickListener(dataBean -> {
            LogUtils.d(TAG, "item click event");
            handleItemClick(dataBean);
        });

        currentCategoryTitle.setOnClickListener(v -> {
            int measuredHeight = mContentList.getMeasuredHeight();

            ToastUtils.showToast("Height-->" + measuredHeight);
        });

        mTwinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//                Toast.makeText(getContext(), "loadMore", Toast.LENGTH_LONG).show();

                if (mCategoryPagerPresenter != null) {
                    mCategoryPagerPresenter.loadMore(mMaterialId);
                }
            }
        });

        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mLooperPagerAdapter.getDataSize() == 0) {
                    return;
                }
                assert mLooperPagerAdapter != null;
                int targetPos = position % mLooperPagerAdapter.getDataSize();
                // 切换指示器
                updateLooperIndicator(targetPos);
            }


            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void handleItemClick(ILinearItemInfo dataBean) {
        TicketUtil.toTicketPage(getContext(), dataBean);
    }

    private void updateLooperIndicator(int targetPos) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point = looperPointContainer.getChildAt(i);

            if (i == targetPos) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point);
            }
        }
    }

    @Override
    protected void initPresenter() {
        mCategoryPagerPresenter = PresenterManager.getInstance().getCategoryPagerPresenter();


        // view 处理 presenter 返回的数据
        mICategoryPagerCallback = new ICategoryPagerCallback() {

            @Override
            public void onContentLoaded(List<HomePagerContent.DataBean> contentList, int categoryId) {

                if (mMaterialId != categoryId) {
                    return;
                }

                mContentAdapter.setDate(contentList);

                LogUtils.d(TAG, "数据的数量" + contentList.size());

                setUpState(STATE.SUCCESS);
            }

            @Override
            public void onNetworkError(int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }
                setUpState(STATE.ERROR);
            }

            @Override
            public void onLoading(int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }
                setUpState(STATE.LOADING);
            }

            @Override
            public void onEmpty(int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }
                setUpState(STATE.EMPTY);
            }

            @Override
            public void onLoadMoreError(int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }

                if (mTwinklingRefreshLayout != null) {
                    mTwinklingRefreshLayout.finishLoadmore();
                }

                ToastUtils.showToast("网络异常请稍后重试");
            }

            @Override
            public void onLoadMoreEmpty(int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }

                if (mTwinklingRefreshLayout != null) {
                    mTwinklingRefreshLayout.finishLoadmore();
                }
                ToastUtils.showToast("没有更多的商品");
            }

            @Override
            public void onLoadMoreLoaded(List<HomePagerContent.DataBean> contents, int categoryId) {
                if (mMaterialId != categoryId) {
                    return;
                }
                mContentAdapter.addData(contents);

                if (mTwinklingRefreshLayout != null) {
                    mTwinklingRefreshLayout.finishLoadmore();
                }
            }


            @Override
            public void onLooperListLoaded(List<HomePagerContent.DataBean> contents) {
                LogUtils.d(TAG, "looper's data coming" + contents.size());
                mLooperPagerAdapter.setData(contents);

                int dx = (Integer.MAX_VALUE / 2) % contents.size();
                int targetPos = (Integer.MAX_VALUE / 2) - dx;

                looperPager.setCurrentItem(targetPos);

                looperPointContainer.removeAllViews();


                // 添加轮播图指示点
                for (int i = 0; i < contents.size(); i++) {
                    View point = new View(getContext());
                    int size = SizeUtils.dip2px(Objects.requireNonNull(getContext()), 8);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);

                    layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
                    layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);

                    point.setLayoutParams(layoutParams);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        point.setBackgroundColor(getContext().getColor(R.color.white));
                    }


                    if (i == 0) {
                        point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
                    } else {
                        point.setBackgroundResource(R.drawable.shape_indicator_point);
                    }

                    looperPointContainer.addView(point);
                }
            }
        };
        mCategoryPagerPresenter.registerViewCallback(mICategoryPagerCallback);
    }

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        if (arguments == null) {
            return;
        }
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIALID);

        LogUtils.d(TAG, "title -- >" + title);
        LogUtils.d(TAG, "materialId -- >" + mMaterialId);

        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.getContentByCategoryId(mMaterialId);
        }

        currentCategoryTitle.setText(title);
    }


    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    /**
     * 用户可见的状态
     */
    @Override
    public void onResume() {
        super.onResume();

        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();

        looperPager.stopLoop();
    }

    /**
     * 释放的时候
     */
    @Override
    protected void release() {
        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.unRegisterViewCallback(mICategoryPagerCallback);
        }
    }
}